package cn.zjh.pet.service.impl;

import cn.zjh.basic.service.impl.BaseServiceImpl;
import cn.zjh.pet.domain.PetType;
import cn.zjh.pet.mapper.PetTypeMapper;
import cn.zjh.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> typeTree() {
        List<PetType> allTypes = petTypeMapper.findAll();

        Map<Long,PetType> map = new HashMap<>();
        //将所有的部门装到map中
        for (PetType petType:allTypes){
            map.put(petType.getId(),petType);
        }

        List<PetType> typeTree = new ArrayList<>();
        for (PetType petType:allTypes){
            if (petType.getPid() == null){
                typeTree.add(petType);
            }else {//有腹肌部门
                //获取当前部门的父级id
                Long pid = petType.getPid();
                //根据父级id获取父级部门
                PetType petType1 = map.get(pid);
                //将自己放到父级部门的集合列表中
                petType1.getchildren().add(petType);
            }
        }

        return typeTree;
    }
}
